﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sponsorship.Domain;
using Raven.Client;
using Sponsorship.Domain.Persons;

namespace Sponsorship.ReadModel.Persons
{
    public class ListOfPersonsHandlers :
        IEventHandler<PersonEntered>,
        IEventHandler<PersonChanged>,
        IEventHandler<PersonDeleted>
    {
        private readonly IDocumentStore m_documentStore;

        public ListOfPersonsHandlers(IDocumentStore store)
        {
            m_documentStore = store;
        }

        public void Handle(PersonEntered domainEvent)
        {
            using (var session = m_documentStore.OpenSession())
            {
                var dto = new ListOfPersonDto
                {
                    AggregateRootId = domainEvent.PersonId,
                    FirstName = domainEvent.FirstName,
                    LastName = domainEvent.LastName,
                    
                };
                session.Store(dto);
                session.SaveChanges(dto, domainEvent);
            }
        }

        public void Handle(PersonChanged domainEvent)
        {
            using (var session = m_documentStore.OpenSession())
            {
                var dto = session.LoadById<ListOfPersonDto>(domainEvent.PersonId);

                dto.FirstName = domainEvent.FirstName;
                dto.LastName = domainEvent.LastName;
  
                session.SaveChanges(dto, domainEvent);
            }
        }

        public void Handle(PersonDeleted domainEvent)
        {
            using (var session = m_documentStore.OpenSession())
            {
                var dto = session.LoadById<ListOfPersonDto>(domainEvent.PersonId);

                dto.IsActive = false;

                session.SaveChanges(dto, domainEvent);
            }
        }
                
    }
}
